import '@wangeditor/editor/dist/css/style.css' // 也可以在 <style> 中 import
import { computed, defineComponent, onBeforeUnmount, ref } from 'vue'
import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
import cloneDeep from 'lodash.clonedeep'
import request from '@/request'
import { useRouter } from 'vue-router'

export default defineComponent({
  name: 'MyEditor',
  components: { Editor, Toolbar },
  setup() {
    const router = useRouter()
    const editorId = 'TangEditor-1'
    // 默认内容
    const defaultContent = [
      {
        type: "paragraph",
        children: [{ text: "一行文字" }],
      },
    ]
    // 注意，深度拷贝 content ，否则会报错
    const getDefaultContent = computed(() => cloneDeep(defaultContent))
    // 编辑器配置
    const editorConfig = { placeholder: '请输入内容...', }
    const customPaste = (editor, event, callback) => {
      // 自定义插入内容
      editor.insertText('')
      // 返回值（注意，vue 事件的返回值，不能用 return）
      callback(true) // 返回 false ，阻止默认粘贴行为
    }
    const blogCover = ref('')// 封面上传路径
    const blogCoverBig = ref('')// 查看大图 图片路径
    const blogCoverBigVisible = ref(false)//查看大图
    const showFrameVisible = ref(true)//添加图片边框
    const showCoverVisible = ref(false)//是否显示阅览图片
    const coverImgList = ref([])//图片集合
    const blogTitle = ref('请输入标题')// 博客标题
    const blogSubTitle = ref('副标题')// 副标题
    const blogRemark = ref('')// 博客备注
    const blogStatus = ref()
    //查看大图
    const showBigCover = () => {
      blogCoverBig.value = blogCover.value
      blogCoverBigVisible.value = true
    }
    // 删除图片
    const removeCoverImg = () => {
      coverImgList.value = []
      showFrameVisible.value = true
      showCoverVisible.value = false
    }
    const fnFileUpload =()=>{
      return new Promise((resolve, reject) => {
        const formatDate = new FormData();
        formatDate.append('file', coverImgList.value[0].raw)
        request('/api/file/upload', 'POST', formatDate, 'multipart/form-data').then(
          (res) => {
            blogCover.value = res.data
            resolve(res.data)
          },
        ).catch(
          () => {
            reject('')
          },
        )
      })
    }
    // 更改图片
    const ChangeCover = (file,fileList) => {
      coverImgList.value = fileList
      blogCover.value = file.url
      fnFileUpload()
      showFrameVisible.value = false
      showCoverVisible.value = true
    }
    const title = ref('')
    // 发表文章按钮
    const buttonDrafts = () => {
      showArticle.value = true
      blogStatus.value = 0
      title.value = '保存草稿'
    }
    const buttonArticle = () => {
      showArticle.value = true
      blogStatus.value = 1
      title.value = '发表文章'
    }

    const showArticle = ref(false)// 弹窗显示
    //弹窗按钮
    const messageCancel = () => {
      showArticle.value = false
    }
    // 确认
    const headleSaveDrafts = () => {
      if (coverImgList.value.length > 0) {
        fnFileUpload().then(() => {insertBlog(blogCover.value,blogStatus.value)})
      } else if (coverImgList.value.length == 0) {
        insertBlog (null,blogStatus.value)
      }
    }
    // 添加接口
    const insertBlog = (newAvatar,blogStatus) => {
      const editor = getEditor(editorId)
      const contentStr = JSON.stringify(editor.children)
      const params = {
        uId:JSON.parse(localStorage.getItem('userInfo')).uId,
        bCover:newAvatar,
        bTitle: blogTitle.value,
        bSTitle:blogSubTitle.value,
        bContent: contentStr,
        remark:blogRemark.value,
        status:blogStatus,
        bLike:'',
        bWatch:'',
        createTime:'',
        updateTime:'',
        bId:'',
        delFlag:'',
        tags:[{
          tName:'1',
          status:'0',
          remark:'1',
          tId:'1',
          createTime:'',
          updateTime:'',
          delFlag:''
        }]
      }
      request('/api/blogs/insert', 'PUT', params).then(
        (res) => {
          toBackBlog()
        },
      )
    }

    // 跳转到上一个界面
    const toBackBlog = () => {
      router.go(-1)
    }
    const headImgSrc = ref('')
    // 及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = getEditor(editorId)
      if (editor == null) return
      // 销毁，并移除 editor
      editor.destroy()
      removeEditor(editorId)
    })
    return {
      headImgSrc,
      title,
      editorId,
      editorConfig,
      getDefaultContent,
      showCoverVisible,
      blogCover,
      blogCoverBigVisible,
      blogCoverBig,
      showFrameVisible,
      coverImgList,
      showArticle,
      blogRemark,
      blogTitle,
      mode: 'default',
      customPaste,
      buttonDrafts,
      buttonArticle,
      toBackBlog,
      messageCancel,
      showBigCover,
      ChangeCover,
      removeCoverImg,
      headleSaveDrafts
    };
  },
  created() {
    this.headImgSrc = JSON.parse(localStorage.getItem('userInfo')).avatar
  }
})
